#include "uart_rfid.h"
#include "string.h"
#include "delay.h"

#define LEN(X) (sizeof(X)/sizeof(uint8_t))

uint8_t data_len=0;//接受缓冲去长度
uint8_t recv_buf[32];



uint8_t readuid[] = {0xaa,0x01,0x01,0x00,0xbb,0x11};
uint8_t halt[] = {0xaa,0x01,0x04,0x00,0xbb,0x14};
 /*
  * @brief  rfid_uart_init 串口初始化
  * @param  None
  * @retval None
  */
void rfid_uart_init(void)
{
	GPIO_InitTypeDef GPIO_Inittypedef;
	USART_InitTypeDef USART_InitTypeDef;
	NVIC_InitTypeDef NVIC_InitTypeDef;
	
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2,ENABLE);
	
	GPIO_Inittypedef.GPIO_Mode = GPIO_Mode_AF_PP;
	GPIO_Inittypedef.GPIO_Pin = GPIO_Pin_2;
	GPIO_Inittypedef.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA,&GPIO_Inittypedef);
	GPIO_Inittypedef.GPIO_Mode = GPIO_Mode_IN_FLOATING;
	GPIO_Inittypedef.GPIO_Pin = GPIO_Pin_3;
	GPIO_Init(GPIOA,&GPIO_Inittypedef);
	
	
	USART_InitTypeDef.USART_BaudRate = 115200;
	USART_InitTypeDef.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
	USART_InitTypeDef.USART_Mode = USART_Mode_Rx|USART_Mode_Tx;
	USART_InitTypeDef.USART_Parity = USART_Parity_No;
	USART_InitTypeDef.USART_StopBits = USART_StopBits_1;
	USART_InitTypeDef.USART_WordLength = USART_WordLength_8b;
	USART_Init(USART2,&USART_InitTypeDef);
	
	NVIC_InitTypeDef.NVIC_IRQChannel = USART2_IRQn;
	NVIC_InitTypeDef.NVIC_IRQChannelCmd = ENABLE;
	NVIC_InitTypeDef.NVIC_IRQChannelPreemptionPriority = 2;
	NVIC_InitTypeDef.NVIC_IRQChannelSubPriority = 2;
	NVIC_Init(&NVIC_InitTypeDef);
	
	USART_ITConfig(USART2,USART_IT_RXNE,ENABLE);
	USART_Cmd(USART2,ENABLE);
}




 /*
  * @brief  rfid_uart_sendcom发送命令
  * @param  com 1 获取uid  4 挂起卡片
  * @retval 1成功，0失败
  */
int8_t rfid_uart_sendcom(uint8_t com)
{
	data_len = 0;
//	uint8_t i;
	memset(recv_buf,0,32);
	if(com!=1&&com!=4)
	{
		return -1;
	}
	switch(com)
	{
		case 1:send_str(readuid,LEN(readuid));break;
		case 4:send_str(halt,LEN(halt));break;
	}
	delay_ms(10);
	if(data_len != 0 && recv_buf[3] == 0x00)
	{
		
		return 1;
	}
	else
	{
		return 0;
	}
}

void send_str(uint8_t *str,uint8_t length)
{
	uint8_t i;
	for(i=0;i<length;i++)
	{
		while(USART_GetFlagStatus(USART2,USART_FLAG_TC) == RESET);
		USART_SendData(USART2,str[i]);
	}
}



 /*
  * @brief  USART2_IRQHandler 串口接受及数据处理的中断处理函数
  * @param  
  * @retval None
  */
void USART2_IRQHandler(void)
{
	uint8_t data;
	if(USART_GetITStatus(USART2,USART_IT_RXNE) != RESET )
	{
		data = USART_ReceiveData(USART2);
		recv_buf[data_len++] = data;
		USART_ClearITPendingBit(USART2,USART_IT_RXNE);//清楚标志位
	}
}
